﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Tilver.Data;
using Weather.BLL.Common;
using Weather.DAL.CoWeather;
using Tilver.Common;

namespace Weather.BLL.Weather
{
    /// <summary>
    /// 雷达和云图显示数据类
    /// </summary>
    public class ProbeImageEO
    {
        /// <summary>
        /// 图片ID
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 站点
        /// </summary>
        public string StationNum { get; set; }

        /// <summary>
        /// 发布时间（yyyy-MM-dd HH:mm:ss）
        /// </summary>
        public DateTime ObservTime { get; set; }
        /// <summary>
        /// 图片类型
        /// </summary>
        public string Stage { get; set; }
        /// <summary>
        /// 图片数据
        /// </summary>
        public byte[] ImgData { get; set; }
    }

    public class ProbeImageBO
    {
        #region 获取卫星云图
        /// <summary>
        /// 卫星云图缓存
        /// </summary>
        /// <param name="stationNum"></param>
        /// <returns></returns>
        public IList<ProbeImageCloudEO> GetProbeImageCloudDO(string stationNum)
        {
            return WebCache.Get(WebCache.ProbeImageCloudData + stationNum, objects => GetProbeImageCloud(stationNum), 600);
        }
        public IList<ProbeImageCloudEO> GetProbeImageCloud(string stationNum)
        {
            var mo = new ProbeImageCloudMO();
            return mo.SelectByStationnum(stationNum, 20, "id");
        }

        public IList<ProbeImageEO> GetCloudImgageDO(string stage)
        {
            return WebCache.Get(WebCache.ProbeImageCloudData + stage, objects => GetCloudImage(stage), 600);
        }
        public IList<ProbeImageEO> GetCloudImage(string stage)
        {
            var list = new List<ProbeImageEO>();
            var para = new List<DbParameter>();
            var factory = DbDataFactory.Create("DATA_PJQXT");
            var sql = new StringBuilder();
            sql.Append(" SELECT TOP 20 [sn],(cast([ldate] as varchar(8))+ [ltime]) as observtime,[pldata] FROM [pjqxt].[dbo].[yunfy2] where [stage] = @stage order by [sn] desc ");
            {
                var p = new SqlParameter("@stage", SqlDbType.VarChar);
                p.Value = stage;
                para.Add(p);
            }

            var sdr = factory.ExecuteReader(sql.ToString(), para);
            while (sdr.Read())
            {
                list.Add(new ProbeImageEO()
                {
                    Id = sdr["sn"] is DBNull ? string.Empty : sdr["sn"].ToString(),
                    ObservTime = sdr["observtime"] is DBNull ? DateTime.Now : ConvertToObservTime(sdr["observtime"].ToString()),
                    Stage = stage,
                    ImgData = sdr["pldata"] is DBNull ? null : (byte[])sdr["pldata"],
                });
            }
            sdr.Close();
            return list.OrderBy(w => w.ObservTime).ToList();
        }
        private DateTime ConvertToObservTime(string str)
        {
            //201411080930
            if (str.Length < 12) return DateTime.Now;
            var dateStr = string.Format("{0}-{1}-{2} {3}:{4}:00", str.Substring(0, 4), str.Substring(4, 2), str.Substring(6, 2),
                                 str.Substring(8, 2), str.Substring(10, 2));
            return dateStr.ToDateTime(DateTime.Now);

        }
        #endregion

        #region 获取雷达云图
        public IList<ProbeImageRadarEO> GetProbeImageRadarDO(string stationNum)
        {
            return WebCache.Get(WebCache.ProbeImageRadarData + stationNum, objects => GetProbeImageRadar(stationNum), 600);
        }
        public IList<ProbeImageRadarEO> GetProbeImageRadar(string stationNum)
        {
            var mo = new ProbeImageRadarMO();
            return mo.SelectByStationnum(stationNum, 20, "id");
        }
        public IList<ProbeImageEO> GetRadarImgageDO(string stationnum)
        {
            return WebCache.Get(WebCache.ProbeImageCloudData + stationnum, objects => GetRadarImage(stationnum), 600);
        }
        public IList<ProbeImageEO> GetRadarImage(string stationnum)
        {
            var list = new List<ProbeImageEO>();

            if (stationnum.ToLower() == "58457")
            {
                /*SELECT top 10 (cast([ldate] as varchar(8))+ [ltime]) as CuTime,[pldata] FROM [pjqxt].[dbo].[radarzw] where stage = 'zjfsl' order by sn desc*/
                var para = new List<DbParameter>();
                var factory = DbDataFactory.Create("DATA_PJQXT");
                var sql = new StringBuilder();
                sql.Append(" SELECT TOP 20 [sn],(cast([ldate] as varchar(8))+ [ltime]) as observtime,[pldata] FROM [pjqxt].[dbo].[radarzw] where stage = 'zjfsl' order by [sn] desc ");
                var sdr = factory.ExecuteReader(sql.ToString(), para);
                while (sdr.Read())
                {
                    list.Add(new ProbeImageEO()
                    {
                        Id = sdr["sn"] is DBNull ? string.Empty : sdr["sn"].ToString(),
                        ObservTime = sdr["observtime"] is DBNull ? DateTime.Now : ConvertToObservTime(sdr["observtime"].ToString()),
                        Stage = stationnum,
                        ImgData = sdr["pldata"] is DBNull ? null : (byte[])sdr["pldata"],
                    });
                }
                sdr.Close();
            }
            else
            {
                var para = new List<DbParameter>();
                var factory = DbDataFactory.Create("DATA_WeatherData");
                var sql = new StringBuilder();
                sql.Append(" SELECT TOP 20 [id],[date],[time],[stationnum],[stage],[elev],[type],[data],[subfix],[renewTime] FROM [co_weatherdata].[dbo].[Probe_Image_Radar] ");
                sql.Append(" where stationnum = @stationnum ");
                if (stationnum.ToLower() == "58556")
                {
                    sql.Append(" and [type] = '230KM雷达拼图' ");
                }
                sql.Append(" order by [id] desc ");
                {
                    var p = new SqlParameter("@stationnum", SqlDbType.VarChar);
                    p.Value = stationnum;
                    para.Add(p);
                }
                var sdr = factory.ExecuteReader(sql.ToString(), para);
                while (sdr.Read())
                {
                    list.Add(new ProbeImageEO()
                    {
                        Id = sdr["id"] is DBNull ? string.Empty : sdr["id"].ToString(),
                        ObservTime = (sdr["date"] is DBNull || sdr["time"] is DBNull) ? DateTime.Now : ConvertToObservTime(sdr["date"].ToString() + sdr["time"].ToString()),
                        Stage = stationnum,
                        ImgData = sdr["data"] is DBNull ? null : (byte[])sdr["data"],
                    });
                }
                sdr.Close();
                /*var factory = DbDataFactory.Create("COWeather");
                var sql = new StringBuilder();
                sql.Append(" SELECT TOP 10 [id],(cast([date] as varchar(8))+ [time]) as observtime,[data] FROM [co_weatherdata].[dbo].[Probe_Image_Radar] where [type] = '230KM雷达拼图' order by [id] desc ");
                var sdr = factory.ExecuteReader(sql.ToString(), para);
                while (sdr.Read())
                {
                    list.Add(new ProbeImageEO()
                    {
                        Id = sdr["id"] is DBNull ? string.Empty : sdr["id"].ToString(),
                        ObservTime = sdr["observtime"] is DBNull ? DateTime.Now : ConvertToObservTime(sdr["observtime"].ToString()),
                        Stage = area,
                        ImgData = sdr["data"] is DBNull ? null : (byte[])sdr["data"],
                    });
                }
                sdr.Close();*/

            }
            return list.OrderBy(w => w.ObservTime).ToList();
        }
        #endregion

        #region 获取雨量图
        public IList<ProbeImageRainEO> GetProbeImageRainDO(string stationNum)
        {
            return WebCache.Get(WebCache.ProbeImageRainData + stationNum, objects => GetProbeImageRain(stationNum), 600);
        }
        public IList<ProbeImageRainEO> GetProbeImageRain(string stationNum)
        {
            var mo = new ProbeImageRainMO();
            return mo.SelectByStationnum(stationNum, 10, "id");
        }
        #endregion
    }
}
